package org.flexharmony.eclipse.nature;

import static org.flexharmony.eclipse.utils.CommonMethods.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;
import org.flexharmony.eclipse.HarmonyDecorator;
import org.flexharmony.eclipse.HarmonyPlugin;
import org.flexharmony.eclipse.HarmonyProjectBuilder;

public class HarmonyProjectNature implements IProjectNature
{
  static public final String NATURE_ID = HarmonyPlugin.PLUGIN_ID + ".nature";
  
  private IProject project;
  
  public HarmonyProjectNature()
  {}

  public void configure() throws CoreException
  {
    addBuilder();
    projectPropertiesChanged(project);
  }

  public void deconfigure() throws CoreException
  {
    HarmonyDecorator.notifyConfigChange();
  }

  public IProject getProject()
  {
    return project;
  }

  public void setProject(IProject project)
  {
    this.project = project;
  }
  
  private void addBuilder() throws CoreException
  {
    IProjectDescription projectDescription = project.getDescription();
    ICommand[] cmds = projectDescription.getBuildSpec();
    for (ICommand cmd : cmds)
    {
      if (cmd.getBuilderName().equals(HarmonyProjectBuilder.BUILDER_ID))
      {
        return;
      }
    }
    
    ICommand cmd = projectDescription.newCommand();
    cmd.setBuilderName(HarmonyProjectBuilder.BUILDER_ID);
    List cmdList = new ArrayList();
    cmdList.addAll(Arrays.asList(cmds));
    cmdList.add(cmd);
    
    projectDescription.setBuildSpec((ICommand[])cmdList.toArray(new ICommand[cmdList.size()]));
    project.setDescription(projectDescription, null);    
  }
}
